package controllers

import (
	"doc-manage/cache"
	"doc-manage/models"
	"doc-manage/pkg"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {

	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名 或者 密码为空",
		}
		c.ServeJSON()
		return
	}
	//密码错误三次，禁止登录
	loginErrorRedisKey := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, loginErrorRedisKey).Int()
	if errCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误3次禁止登录",
		}
		c.ServeJSON()
		return
	}

	var err error
	var user models.User
	err = models.DB.Table("users").Where("username = ?", username).First(&user).Debug().Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户查询失败",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5Str(password) {

		cache.Rdb.Incr(cache.Ctx, loginErrorRedisKey) //自增+1
		//pwdCountErr, _ := cache.Rdb.Get(cache.Ctx, loginErrorRedisKey).Int()
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, loginErrorRedisKey, 3, time.Hour*2)
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "密码错误次数3次，封禁2个小时",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) List() {
	username := c.GetString("username")
	page, _ := c.GetInt("page", 1)   //页码
	limit, _ := c.GetInt("limit", 2) //每页数量
	offset := (page - 1) * limit

	dataListKey := "data_list_" + username + "_page_" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, dataListKey).Result()

	var userList []models.User
	if cacheJson == "" {
		//从mysql查询数据
		query := models.DB.Table("users")
		if username != "" {
			query = query.Where("username like ?", "%"+username+"%")
		}
		query.Limit(limit).Offset(offset).Find(&userList)

		jsonData, _ := json.Marshal(userList)
		cache.Rdb.Set(cache.Ctx, dataListKey, jsonData, time.Hour*2)
	} else {
		//从redis获取数据
		json.Unmarshal([]byte(cacheJson), &userList)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": userList,
		"msg":  "success",
	}
	c.ServeJSON()
	return

}

func (c *UserController) Detail() {
	id, _ := c.GetInt("id")

	dataListKey := "data_id_" + strconv.Itoa(id)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, dataListKey).Result()

	var user models.User
	if cacheJson == "" {
		//从mysql读取
		models.DB.Table("users").Where("id = ?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, dataListKey, jsonData, time.Hour*2)
	} else {
		//从redis获取数据
		json.Unmarshal([]byte(cacheJson), &user)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Dts() {

	id, _ := c.GetInt("id")
	models.DB.Table("users").
		Joins("left join user_role_relations on user_role_relations.uid = users.id").
		Joins("left join roles on roles.id = user_role_relations.rid").
		Joins("left join role_node_relations on role_node_relations.rid = roles.id").
		Joins("left join nodes on nodes.id = role_node_relations.nid").
		Where("users.id = ?", id).Debug().Find(&models.User{})

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}
